package com.CST.service.impl.ys;

import com.CST.common.BaseEntity;
import com.CST.dto.ys.YsDepartmentDTO;
import com.CST.entity.ys.YsDepartment;
import com.CST.mapper.cst.ys.YsDepartmentMapper;
import com.CST.mapper.cst.ys.YsSubjectDepartmentMapper;
import com.CST.service.ys.YsDepartmentService;
import com.CST.util.ExcelTransfer;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author qtx
 * @since 2023-04-20
 */
@Service
public class YsDepartmentServiceImpl extends ServiceImpl<YsDepartmentMapper, YsDepartment> implements YsDepartmentService {

    private final ExcelTransfer<YsDepartment> excelTransfer;

    @Autowired
    private YsSubjectDepartmentMapper ysSubjectDepartmentMapper;

    public YsDepartmentServiceImpl(ExcelTransfer<YsDepartment> excelTransfer) {
        this.excelTransfer = excelTransfer;
    }

    @Override
    public IPage<YsDepartment> listYsDepartmentPage(YsDepartmentDTO dto) {
        return page(dto.getPage(), Wrappers.lambdaQuery(YsDepartment.class)
                .eq(BaseEntity::getDeleteFlag, Boolean.FALSE)
                .like(
                        StringUtils.isNotBlank(dto.getDepartmentCode()), YsDepartment::getDepartmentCode,
                        dto.getDepartmentCode())
                .like(StringUtils.isNotBlank(dto.getDepartmentName()), YsDepartment::getDepartmentName,
                        dto.getDepartmentName()).orderByDesc(YsDepartment::getCreateTime));
    }

    @Override
    public List<YsDepartment> listYsDepartment(String name, Integer status,Integer manageStatus) {
        return list(Wrappers.lambdaQuery(YsDepartment.class)
                .eq(BaseEntity::getDeleteFlag, Boolean.FALSE)
                .eq(status != null, YsDepartment::getStatus, status)
                .eq(manageStatus != null, YsDepartment::getManageStatus, manageStatus)
                .like(StringUtils.isNotBlank(name), YsDepartment::getDepartmentName, name));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateYsDepartment(YsDepartment entity) {
        Optional.ofNullable(entity.getDepartmentCode())
                .orElseThrow(() -> new RuntimeException("部门编码为空。"));

        // 如果在预算科目管理中引用了就不允许关闭
        if (entity.getManageStatus() !=null && !entity.getManageStatus()){
            int count = ysSubjectDepartmentMapper.selectByDeptId(entity.getId());
            if (count > 0 ){
                throw new RuntimeException("该部门已经在预算科目管理模块中被引用，请取消引用后再关闭管理职能");
            }
        }

        YsDepartment one = getOne(Wrappers.lambdaQuery(YsDepartment.class)
                .eq(BaseEntity::getDeleteFlag, Boolean.FALSE)
                .eq(YsDepartment::getDepartmentCode, entity.getDepartmentCode())
                .ne(entity.getId() != null, BaseEntity::getId, entity.getId()));
        if (Objects.isNull(one)) {
            if (entity.getId() != null) {
                entity.setDepartmentCode(null);
            }
            return saveOrUpdate(entity);
        } else {
            throw new RuntimeException("部门编码重复。");
        }
    }

    @Override
    public boolean removeYsDepartmentById(Long id) {
        YsDepartment byId = getById(id);
        YsDepartment ysDepartment = Optional.ofNullable(byId)
                .orElseThrow(() -> new RuntimeException("部门不存在。"));
        if (ysDepartment.getNum() == null || ysDepartment.getNum() == 0) {
            return update(Wrappers.lambdaUpdate(YsDepartment.class)
                    .set(BaseEntity::getDeleteFlag, Boolean.TRUE)
                    .eq(BaseEntity::getId, id));
        } else {
            throw new RuntimeException("部门已被引用。");
        }
    }

    @Override
    public void importExcelYsDepartment(MultipartFile file) {
        excelTransfer.importExcel(file, this, YsDepartment.class);
    }

    @Override
    public void exportExcelYsDepartment(HttpServletResponse response) {
        excelTransfer.exportExcel(response, list(Wrappers.lambdaQuery(YsDepartment.class)
                .eq(BaseEntity::getDeleteFlag, Boolean.FALSE)), "预算部门", "sheet", YsDepartment.class);
    }

    @Override
    public void exportExcelYsDepartmentDemo(HttpServletResponse response) {
        excelTransfer.exportExcel(response, new ArrayList<>(), "预算部门", "sheet", YsDepartment.class);
    }

    @Override
    public List<YsDepartment> listYsDepartmentCb(String name) {
        return baseMapper.selectListCb(name);
    }

    @Override
    public List<YsDepartment> listYsManageAssetDepartment() {
        return baseMapper.selectManageAssetDepartment();
    }
}
